﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataModel;
using System.Net;
using System.IO;
using Tracy.BTParser;
using SharedLib.BasicServices.MessageFramework;
using Tracy.Messages;

namespace Tracy.Handlers
{
    public class AssignMediaFileHandler : TaskMessageHandler<TaskMessage<Resource, List<MediaFile>>>
    {
        protected override void ProcessMessage(TaskMessage<Resource, List<MediaFile>> msg)
        {
            if (msg != null)
            {
                Resource res = msg.GenericData;
                if (res != null)
                {
                    msg.Result = BuildMediaFiles(res);
                }
            }
        }

        private static List<MediaFile> BuildMediaFiles(Resource res)
        {
            List<MediaFile> rtn = new List<MediaFile>();
            if (res.GetResourceType() == "BT")
            {
                //Download and Parse bit torrent file
                string tempFile = Path.GetTempPath() + res.GetFileName();
                WebClient client = new WebClient();
                client.DownloadFile(res.Url, Path.GetTempPath() + res.GetFileName());
                Torrent t = new Torrent(tempFile);
                string locationBase = (t.FileNameList.Count > 1) ? t.Name + "\\" : "";//Folder will be required if there are multiple files

                List<string> existingFileNames = new List<string>();
                foreach(MediaFile existingFile in TracyBus.Instance.MediaFileProvider.GetItemByResource(res))
                {
                    existingFileNames.Add(existingFile.FileName);
                }

                foreach (string fileName in t.FileNameList)
                {
                    if (!existingFileNames.Contains(fileName))
                    {
                        if (MediaFile.WillDownload(fileName))
                        {
                            int lastSlashIndex = fileName.LastIndexOf("\\");
                            MediaFile newFile = new MediaFile();
                            newFile.FileName = fileName.Substring(lastSlashIndex + 1);
                            newFile.Location = (lastSlashIndex > 0) ? locationBase + fileName.Substring(0, lastSlashIndex) : locationBase;
                            newFile.Resource = res;
                            if (MediaFile.IsVisible(fileName)) newFile.Visible = "true";
                            TracyBus.Instance.MediaFileProvider.AddItem(newFile);
                            rtn.Add(newFile);
                        }
                    }
                }
                File.Delete(tempFile);
            }//TODO: Emule
            return rtn;
        }
    }
}
